package com.bosssoft.trainee.nontax.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bosssoft.trainee.nontax.annotation.UserLoginToken;
import com.bosssoft.trainee.nontax.common.CodeMsg;
import com.bosssoft.trainee.nontax.common.Result;
import com.bosssoft.trainee.nontax.entity.dto.RoleDTO;
import com.bosssoft.trainee.nontax.entity.po.Role;
import com.bosssoft.trainee.nontax.entity.po.User;
import com.bosssoft.trainee.nontax.entity.vo.RoleQueryVO;
import com.bosssoft.trainee.nontax.entity.vo.RoleVO;
import com.bosssoft.trainee.nontax.mapper.RoleMapper;
import com.bosssoft.trainee.nontax.service.RoleService;
import com.bosssoft.trainee.nontax.service.TokenService;
import com.bosssoft.trainee.nontax.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * @author liuqiang
 * @date 2022/6/18 23:14
 */
@Slf4j
@Controller
@RequestMapping("userRole")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserService userService;

    @Autowired
    TokenService tokenService;


    /**
     * 获取角色信息
     *
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @GetMapping("/list")
    public Result<Object> getRole() {
        List<RoleDTO> list = roleService.getList();
        List<RoleVO> listVo = new ArrayList<>();
        for (RoleDTO roleDTO : list) {
            RoleVO roleVo = new RoleVO();
            BeanUtils.copyProperties(roleDTO, roleVo);
            listVo.add(roleVo);
        }
        //尝试获取通过Token获取用户id
        log.info("id:{}", tokenService.getUserId());
        return Result.success(listVo);
    }

    /**
     * 新增/插入角色
     *
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @PostMapping("/insertRole")
    public Result<Object> insertRole(@Valid @RequestBody RoleVO roleVo) {
        RoleDTO roleDto = new RoleDTO();
        BeanUtils.copyProperties(roleVo, roleDto);
        roleDto.setUpdateId(Integer.valueOf(tokenService.getUserId()));
        roleService.saveRole(roleDto);
        return Result.success();
    }

    /**
     * 修改角色
     *
     * @param roleVO rolevo
     * @return 统一结果
     */
    @UserLoginToken
    @ResponseBody
    @PostMapping("/updateRole")
    public Result<Object> updateRole(@Valid @RequestBody RoleVO roleVO) {
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(roleVO, roleDTO);
        roleDTO.setUpdateId(Integer.valueOf(tokenService.getUserId()));
        if (roleService.updateRole(roleDTO)) {
            return Result.success();
        } else {
            return Result.error(CodeMsg.ROLE_NOT_EXSIST);
        }
    }

    /**
     * 根据id删除角色信息
     *
     * @param id 角色id
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @GetMapping("/delete/{id}")
    public Result<Object> deleteRole(@PathVariable("id") Integer id) {
        List<User> list = userService.list();
        int userRoleId = -1;
        Role role = roleService.getById(id);
        if (role == null) {
            //角色不存在
            userRoleId = 2;
        } else {
            for (User user : list) {
                if (Objects.equals(user.getUserRole(), role.getRoleName()))
                //被引用无法删除
                {
                    userRoleId = 0;
                    break;
                }
            }
        }
        if (userRoleId == -1) {
            roleService.removeById(id);
            return Result.success();
        } else if (userRoleId == 2) {
            return Result.error(CodeMsg.ROLE_NOT_EXSIST);
        } else {
            return Result.error(CodeMsg.DATA_REFERENCED);
        }
    }


    /**
     * 分页
     *
     * @param pageNum  pageNum
     * @param pageSize pageSize
     * @return result
     */
    @ResponseBody
    @GetMapping("/test")
    public Result<Object> getRoleList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        List<RoleDTO> list = roleService.getListDTO(pageNum, pageSize);
        List<RoleVO> listVo = new ArrayList<>();
        for (RoleDTO roleDTO : list) {
            RoleVO roleVo = new RoleVO();
            BeanUtils.copyProperties(roleDTO, roleVo);
            listVo.add(roleVo);
        }
        Page<Role> pageInfo = new Page<>(pageNum, pageSize);
        roleService.page(pageInfo);

        log.info("总数据:{}", pageInfo.getTotal());
        log.info("总页数:{}", pageInfo.getPages());

        Map<String, Object> map = new HashMap<>();
        map.put("role", listVo);
        map.put("pages", pageInfo.getPages());
        map.put("total", pageInfo.getTotal());
        map.put("currentPage", pageInfo.getCurrent());
        return Result.success(map);
    }

    /**
     * 多条件查询+模糊查询
     *
     * @param roleQueryVO roleQueryVO
     * @return result
     */
    @UserLoginToken
    @ResponseBody
    @GetMapping("/findRole")
    public Result<Object> findRole(@RequestBody RoleQueryVO roleQueryVO) {

        List<RoleDTO> list = roleService.findRole(roleQueryVO);
        if (list.isEmpty()) {
            return Result.error(CodeMsg.ROLE_NOT_EXSIST);
        } else {
            List<RoleVO> roleVOS = new ArrayList<>();
            for (RoleDTO roleDTO : list) {
                RoleVO roleVO = new RoleVO();
                BeanUtils.copyProperties(roleDTO, roleVO);
                roleVOS.add(roleVO);
            }
            return Result.success(roleVOS);
        }
    }

    @ResponseBody
    @GetMapping("/tests")
    public String test() {

        return tokenService.getUserId();
    }
}
